<template>
  <!-- 编辑-->
  <div class="page commissioned-dialog">
    <el-form
      :rules="rules"
      :model="form"
      ref="add-form"
      inline
      label-width="140px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="公司名称" prop="outOrgName">
            <el-input
              v-model.trim="form.outOrgName"
              size="small"
              :disabled="disabled"
              :maxlength="20"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外包公司代码" prop="divisionCode">
            <el-input
              v-model.trim="form.divisionCode" 
              size="small"
              :disabled="num !== 'created'"
              :maxlength="20"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="社会信用代码" prop="registrationCode">
            <el-input v-model.trim="form.registrationCode" size="small" :disabled='disabled' :maxlength="18"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人姓名" prop="contactsName">
            <el-input
              v-model.trim="form.contactsName"
              size="small"
              :disabled="disabled"
              :maxlength="10"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人电话" prop="contactsPhone">
            <el-input
              v-model.trim="form.contactsPhone"
              size="small"
              max-length="11"
              :disabled="disabled"
              :maxlength="11"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系地址" prop="contactsArea">
            <el-input
              v-model.trim="form.contactsArea"
              size="small"
              :disabled="disabled"
              :maxlength="13"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系邮箱" prop="contactsEmail">
            <el-input
              v-model.trim="form.contactsEmail"
              size="small"
              :maxlength="25"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="机构管理员" prop="orgAdmin">
            <el-input
              v-model.trim="form.orgAdmin"
              size="small"
              :disabled="disabled"
              :maxlength="25"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签约日期" prop="signTime">
            <el-date-picker
              v-model="form.signTime"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="disabled"
              placeholder="选择日期"
              @change="timeChangeBtn"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同到期日期" prop="contractDueDate">
            <el-date-picker
              v-model="form.contractDueDate"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="disabled"
              placeholder="选择日期"
              @change="timeChangeEndBtn"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分案状态" prop="divisionStatus">
            <el-select
              size="small"
              v-model="form.divisionStatus"
              placeholder="请选择分案状态"
              :disabled="disabled"
            >
              <el-option label="开启" value="0"></el-option>
              <el-option label="关闭" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="可催收区域" prop="selectedCitysList" style="width:320px">
            <el-button type="primary" size="small" @click="dialog.area=true" :disabled="disabled">选择区域</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="city-list">
            <span class="my-tag" v-for="(tag, index) in selectedCitysList" :key="index">{{tag.label}}</span>
          </div>
        </el-col>
        
        <el-col :span="23">
          <el-form-item label="备注" prop="remark" class="remark">
            <el-input
              type="textarea"
              v-model.trim="form.remark"
              :disabled="disabled"
              :autosize="{ minRows: 2, maxRows: 4 }"
              :maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="operate-buttons">
      <el-button @click="cancel">取消</el-button>
      <el-button @click="commit">确定</el-button>
    </div>

    <el-dialog
      title="选择区域"
      :center="true"
      :visible.sync="dialog.area"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @open="
        $nextTick(() => {
          $refs['area'].onSelectedCitysChange();
        })
      "
      @close="$refs['area'].close()"
      append-to-body
    >
      <area-selection
        ref="area"
        :selectedCitys="selectedCitys"
      ></area-selection>
      <span slot="footer" class="operate-buttons">
        <el-button type="primary" size="small" @click="closeArea"
          >关 闭</el-button
        >
        <el-button type="primary" size="small" @click="saveArea"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { State, Mutation, Getter, Action, namespace } from "vuex-class";
import { Emit, Prop, Watch } from "vue-property-decorator";
import clone from "clone";
import AreaSelection from "~/components/common/area-selection.vue";
import { CityService } from "~/utils/city.service";
import { OutsourceCommissionedService } from "~/services/domain-service/outsource-commissioned-manage.service";
import { UserService } from "~/services/management-service/user.service";

@Component({
  components: {
    AreaSelection
  }
})
export default class CommissionedDialog extends Vue {
  @Dependencies(OutsourceCommissionedService)
  private outsourceCommissionedService: OutsourceCommissionedService;
  @Dependencies(UserService)
  private userService: UserService;
  @Action private getAllOutsource;
  @Prop({ required: true })
  @Prop()
  private caseRow: any;
  private form: any = {
    outOrgName: '',
    registrationCode: '', // 统一社会信用代码
    divisionCode: '', // 分案代码
    contactsName: '',
    contactsPhone: '',
    contactsArea: '',
    contactsEmail: '',
    orgAdmin: '', //机构管理员
    signTime: '', //签约日期
    divisionStatus: "", //分案状态
    contractDueDate: "",
    remark: "",
    companyType: '',
    organizationType: '',
    areaId: '',
    collectionArea: []
  };
  @Prop() private num: any;
  private disabled: boolean = false;
  private clearSelectedCitysList: boolean = false;
  private dialog: any = {
    area: false
  };
  private areaIds = [];

  private proinviceList: any[] = []; // 省
  private cityList: any[] = []; //市
  private areaCodeIds: string = ""; //催收区域id
  private selectedCitysList: any[] = [];

  //验证
  private rules: any = {
    outOrgName: [{ required: true, message: '请填写公司名称', trigger: 'blur' }],
    divisionCode: [{ required: true, message: '请填写外包公司代码', trigger: 'blur' },
      { pattern: /^[A-Za-z0-9]+$/, message: "请输入英文字母或数字", trigger: "blur" }
    ],
    registrationCode: [
      { required: true, message: '请填写统一社会信用代码', trigger: 'blur' },
      { pattern: /^[A-Za-z0-9]+$/, message: "请填写合法的统一社会信用代码", trigger: 'blur'},
    ],
    contactsName: [
        { required: true, message: '请填写联系人姓名', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: "请输入合法的联系人姓名", trigger: 'blur'},
    ],
    contactsPhone: [
      { required: true, message: '请填写联系人电话', trigger: 'blur' },
      { pattern: /^\+?[0-9][0-9]*$/, message: "联系电话应输入数字", trigger: 'blur'},
      { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: "请输入合法的联系电话",trigger: "blur",},
    ],
    contactsEmail: [
      { required: true, message: '请填写联系邮箱', trigger: 'blur' },
      { required: true, pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,  message: '请填写正确的联系邮箱', trigger: 'blur' },
    ],
    contactsArea: [{ required: true, message: '请填写联系地址', trigger: 'blur' }],
    orgAdmin: [{ required: true, message: '请填写机构管理员', trigger: 'blur' }],
    signTime: [{ required: true, message: '请选择签约日期', trigger: 'blur' }],
    contractDueDate: [{ required: true, message: '请选择合同到期日期', trigger: 'blur' }],

    divisionStatus: [
      { required: true, message: "请选择分案状态", trigger: "blur" }
    ]
    // organi zationType: [{ required: true, message: '请选择机构类型', trigger: 'blur' }],
  };
  
  @Watch("num", { immediate: true })
  private changeNum() {
    this.disabled = this.num === 'look'
  }
  @Watch("caseRow")  private onCaseRowChange() {
    this.selectedCitysList = []
    this.form = this.caseRow;
    this.formData();
  }

  get selectedCitys() {
    return this.selectedCitysList.map(x => x.value);
  }

  private timeChangeBtn() {
    const PlanEndTime = new Date(this.form.signTime)
    const PlanStartTime = new Date(this.form.contractDueDate) 
    if(PlanEndTime.getTime() > PlanStartTime.getTime()){
      this.$message("签约日期不能大于合同到期日期!")
      this.form.signTime = ""
      return false;
    }
  }
  private timeChangeEndBtn() {
    const PlanEndTime = new Date(this.form.signTime)
    const PlanStartTime = new Date(this.form.contractDueDate) 
    if(PlanEndTime.getTime() > PlanStartTime.getTime()){
      this.$message("合同到期日期不能小于签约日期!")
      this.form.contractDueDate = ""
      return false;
    }
  }

  //数据回显
  private formData() { // 数据回显
    this.form = { ...this.caseRow }
    // this.selectedCitysList = Array.from(JSON.parse(this.caseRow.cityName === undefined ? '{}' : this.caseRow.cityName))
    this.selectedCitysList = Array.from(JSON.parse(this.caseRow.collectionArea === undefined ? [] : this.caseRow.collectionArea))
  }

  //获取省数据
  private getProvinces() {
    this.proinviceList = CityService.getCityData({ level: 1 });
  }

  //获取市
  private getCitys(provinceId) {
    this.cityList = this.$city.getCityData({ level: 1, id: provinceId }); // 城市列表
  }

  private selectedCitysClose() {
    this.selectedCitysList = (this.$refs.area as AreaSelection).getCheckedCitys();
  }

  
  /**
   * 确认
   */
  private commit() {
    const addForm: any = this.$refs["add-form"];
    this.areaCodeIds = this.selectedCitysList.map(v => v.value).join()
    const param = {
      areaCode: this.form.areaCode,
      areaName: this.form.areaName,
      cityName: JSON.stringify(this.selectedCitysList),
      // id: this.type === 'add' ? '' : this.caseRow.id
    }
    const [prinPrid, prinCityid, prinCtyid] = this.areaIds;
    this.form.areaId = prinCtyid || prinCityid || prinPrid;
    this.form.collectionArea = param.cityName
    this.form.areaName = param.areaName
    this.form.areaCode = param.areaCode
    addForm.validate((valid) => {
      if (!valid) return false;
      // this.form.divisionCode = parseInt(this.form.divisionCode)
      if (this.num === 'created') {
        this.userService.addOrgInfo(this.form).subscribe(data => {
          this.caller()
        });
      } else if (this.num === 'update') {
        this.form.createTime =
        this.$filter.dateTimeFormat(this.form.createTime) + "";
        this.userService.updateOrgInfo(this.form).subscribe(data => {
          this.caller()
        });
      } else {
        const addForm: any = this.$refs["add-form"];
        addForm.resetFields();
        this.areaCodeIds = "";
        this.$emit("close");
        this.$emit("refreshData");  // 刷新databox
      }
    });
  }

  private caller(){
    //   重置form表单xr
    const addForm: any = this.$refs["add-form"];
    addForm.resetFields();
    // this.form = {};
    this.areaCodeIds = "";
    //   关闭dialog
    this.$emit("close");
    this.$message.success("保存成功!");
    //   刷新databox
    this.$emit("refreshData");
    // 刷新store中的委外方
    this.getAllOutsource()
  }

  /**
   * 取消
   */
  private cancel() {
    // //   重置form表单
    const addForm: any = this.$refs["add-form"];
    addForm.resetFields();
    // this.formData();
    this.$emit("close");
  }
  /**
   * 初始化参数
   */
  private initProperty () {
    this.form = {
      outOrgName: '',
      registrationCode: '', // 统一社会信用代码
      divisionCode: '', // 分案代码
      contactsName: '',
      contactsPhone: '',
      contactsArea: '',
      contactsEmail: '',
      orgAdmin: '', //机构管理员
      signTime: '', //签约日期
      divisionStatus: "", //分案状态
      contractDueDate: "",
      remark: "",
      companyType: '',
      organizationType: '',
      areaId: '',
      collectionArea: []
    };
  }

  private closeArea() {
    this.dialog.area = false;
  }
  private saveArea () {
    this.selectedCitysClose();
    this.dialog.area = false;
  }
}
</script>
<style lang="less" scoped>
.data-grid {
  margin-bottom: 10px;
}

.header {
  border: solid 1px #dee1e5;
  border-bottom: 0px;
  height: 40px;
  line-height: 40px;
}
#app .page .el-form .el-form-item .el-select.address .el-input {
  width: 100%;
}
.my-tag {
  display: inline-block;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 0 10px;
  height: 32px;
  line-height: 30px;
  font-size: 12px;
  color: #409eff;
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border: 1px solid rgba(64, 158, 255, 0.2);
  white-space: nowrap;
}
.city-list {
  margin-bottom: 20px;
  padding: 0 20px;
}
</style>
<style lang="less">
.commissioned-dialog{
  .remark{
    width: 100%;
    .el-form-item__content{
      width: 74.5%;
    }
  }
}

</style>
